<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加权限"
    width="500px"
    @close="handleClose"
  >
    <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="授权类型" prop="grantType">
        <el-radio-group v-model="formData.grantType">
          <el-radio label="user">用户</el-radio>
          <el-radio label="role">角色</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item v-if="formData.grantType === 'user'" label="用户" prop="userId">
        <el-select 
          v-model="formData.userId" 
          placeholder="请选择用户" 
          filterable 
          v-loading="loadingUsers"
          style="width: 100%"
        >
          <el-option
            v-for="user in userList"
            :key="user.userId"
            :label="user.userName"
            :value="user.userId"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item v-if="formData.grantType === 'role'" label="角色" prop="roleId">
        <el-select 
          v-model="formData.roleId" 
          placeholder="请选择角色" 
          filterable 
          v-loading="loadingRoles"
          style="width: 100%"
        >
          <el-option
            v-for="role in roleList"
            :key="role.roleId"
            :label="role.roleName"
            :value="role.roleId"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="权限类型" prop="permissionType">
        <el-checkbox-group v-model="selectedPermissions">
          <el-checkbox label="read">读取</el-checkbox>
          <el-checkbox label="write">写入</el-checkbox>
          <el-checkbox label="delete">删除</el-checkbox>
          <el-checkbox label="share">分享</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { permissionApi, type PermissionGrantParams } from '@/api/cd'
import { listUser } from '@/api/system/user'
import { listRole } from '@/api/system/role'
import type { UserVO } from '@/api/system/user/types'
import type { RoleVO } from '@/api/system/role/types'

interface Props {
  visible: boolean
  resourceType: string
  resourceId: number | string
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const formRef = ref<FormInstance>()
const loading = ref(false)
const loadingUsers = ref(false)
const loadingRoles = ref(false)
const selectedPermissions = ref<string[]>([])
const userList = ref<UserVO[]>([])
const roleList = ref<RoleVO[]>([])

const formData = ref({
  grantType: 'user' as 'user' | 'role',
  userId: undefined as number | string | undefined,
  roleId: undefined as number | string | undefined
})

const rules = {
  grantType: [{ required: true, message: '请选择授权类型', trigger: 'change' }],
  userId: [{ required: true, message: '请选择用户', trigger: 'change' }],
  roleId: [{ required: true, message: '请选择角色', trigger: 'change' }]
}

// 加载用户列表
const loadUsers = async () => {
  if (loadingUsers.value) return
  loadingUsers.value = true
  try {
    const response = await listUser({
      status: '0',
      pageNum: 1,
      pageSize: 1000
    })
    console.log('用户列表响应:', response)
    userList.value = response.rows || []
    console.log('用户列表:', userList.value.length, '个用户')
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    loadingUsers.value = false
  }
}

// 加载角色列表
const loadRoles = async () => {
  if (loadingRoles.value) return
  loadingRoles.value = true
  try {
    const response = await listRole({
      status: '0',
      pageNum: 1,
      pageSize: 1000
    })
    console.log('角色列表响应:', response)
    roleList.value = response.rows || []
    console.log('角色列表:', roleList.value.length, '个角色')
  } catch (error) {
    console.error('加载角色列表失败:', error)
    ElMessage.error('加载角色列表失败')
  } finally {
    loadingRoles.value = false
  }
}

// 监听对话框打开，加载用户和角色列表
watch(() => props.visible, async (newVal) => {
  if (newVal) {
    await Promise.all([loadUsers(), loadRoles()])
  }
})

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    if (selectedPermissions.value.length === 0) {
      ElMessage.warning('请至少选择一种权限类型')
      return
    }
    
    loading.value = true
    try {
      const params: PermissionGrantParams = {
        resourceType: props.resourceType,
        resourceId: props.resourceId,
        permissionTypes: selectedPermissions.value
      }
      
      if (formData.value.grantType === 'user') {
        params.userId = formData.value.userId
        await permissionApi.grantUserPermission(params)
      } else {
        params.roleId = formData.value.roleId
        await permissionApi.grantRolePermission(params)
      }
      
      // 不显示成功提示，由父组件统一处理
      emit('success')
      dialogVisible.value = false
    } catch (error) {
      console.error('添加权限失败:', error)
      ElMessage.error('添加权限失败')
    } finally {
      loading.value = false
    }
  })
}

const handleClose = () => {
  dialogVisible.value = false
  selectedPermissions.value = []
  formData.value = {
    grantType: 'user',
    userId: undefined,
    roleId: undefined
  }
}
</script>

<style scoped lang="scss">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
